﻿using System;
using System.Linq;
using MaternityHospitalPatients.Data;

namespace MaternityHospitalPatients.Repository
{
    public class DataRepository
    {
        public void SavePatientRecord(PatientRecords patientRecord, Areas area, Departments department)
        {
            using (var manager = ConnectionFactory.GetNewConnection())
            {
                try
                {
                    Areas ar = manager.Areas.FirstOrDefault(a => a.ID == patientRecord.AreaID);
                    if (ar == null)
                    {
                        manager.Areas.InsertOnSubmit(area);
                        manager.SubmitChanges();
                    }
                  

                    Departments dpt = manager.Departments.FirstOrDefault(d => d.Title.ToUpper() == department.Title.ToUpper());
                    if (dpt == null)
                    {
                        manager.Departments.InsertOnSubmit(department);
                        manager.SubmitChanges();
                        patientRecord.DepartmentID = department.ID;
                    }
                    else
                    {
                        patientRecord.DepartmentID = dpt.ID;
                    }
                  
                    //patientRecord.Department = department;
                    manager.PatientRecords.InsertOnSubmit(patientRecord);
                    manager.SubmitChanges();
                }
                catch (Exception)
                {
                    
                }
            }
        }

        public IQueryable<PatientRecords> GetPatientRecords()
        {
            using (var manager = ConnectionFactory.GetNewConnection())
            {
                return manager.PatientRecords;
            }
        }

        public IQueryable<Debtors> GetDebtors()
        {
            using (var manager = ConnectionFactory.GetNewConnection())
            {
                return manager.Debtors;
            }
        }
    }
}